package com.mti.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.snowflake.KeyWorker;
import com.mti.constant.ArmingTaskEnum;
import com.mti.dao.model.ArmingTaskRelationEntity;
import com.mti.dao.model.LfZdryArmingTaskOperateLog;
import com.mti.dao.model.LfZdryEntity;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.mapper.ArmingTaskRelationMapper;
import com.mti.service.IArmingTaskRelationLogService;
import com.mti.service.IArmingTaskRelationService;
import com.mti.service.ILfZdryService;
import com.mti.service.ISpecialPersonService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @company 上海道枢信息科技-->
 * @anthor created by zhangmingxin
 * @date 2019/9/12
 * @change
 * @describe describe
 **/
@Service
@AllArgsConstructor
public class ArmingTaskRelationServiceImpl extends ServiceImpl<ArmingTaskRelationMapper,ArmingTaskRelationEntity> implements IArmingTaskRelationService {
    private final IArmingTaskRelationLogService logService;
    private final RequestUtils requestUtils;
    private final ILfZdryService zdryService;
    @Override
    public void approveArmingTask(String rid, Integer status, String description, ServerWebExchange exchange) {
        String[] ids = rid.split(",");
        if(ids.length<=0)
            throw new BusinessException(500,"关联ID不能为空");
        if(status<1 || status>4)
            throw new BusinessException(500,"非法操作状态");
        Collection<String> rids = Arrays.asList(ids);
        //查询是否有未上报人员
        Collection<ArmingTaskRelationEntity> unReportPerson = this.list(new LambdaQueryWrapper<ArmingTaskRelationEntity>().in(ArmingTaskRelationEntity::getId,rids).and(it->it.eq(ArmingTaskRelationEntity::getApproveStatus,ArmingTaskEnum.REPORTING_TYPE.ordinal()).or().eq(ArmingTaskRelationEntity::getApproveStatus,ArmingTaskEnum.RECALL_TYPE.ordinal())));
        if(unReportPerson!=null && unReportPerson.size()>0)
            throw new BusinessException(500,"审批人员中存在未上报人员");
        Collection<ArmingTaskRelationEntity> relationEntities = this.listByIds(rids);
        Map<String,List<LfZdryEntity>> zdryList = zdryService.listByIds(relationEntities.stream().map(ArmingTaskRelationEntity::getSpId).collect(Collectors.toList())).stream().collect(Collectors.groupingBy(LfZdryEntity::getId));
        AtomicReference<String> operation = new AtomicReference<>();
        List<LfZdryArmingTaskOperateLog> logs = new ArrayList<>();
        AccountBo accountBo = requestUtils.getCurrentUser(exchange);
        if(Integer.valueOf(1).equals(status)){//通过
            List<ArmingTaskRelationEntity> passEntities = relationEntities.stream()
                    .filter(item->item.getApproveStatus()<ArmingTaskEnum.FINISH_TYPE.ordinal())
                    .peek(item->{
                        item.setDescription(description);
                        if(item.getApproveStatus().equals(ArmingTaskEnum.RECALL_TYPE.ordinal())) {
                            item.setApproveStatus(ArmingTaskEnum.WAIT_POLICE_TYPE.ordinal());
                        } else{
                            if(item.getApproveStatus()<ArmingTaskEnum.WAIT_POLICE_TYPE.ordinal()){
                                operation.set("通过区县警种审核");
                                item.setApproveStatus(item.getApproveStatus()+1);
                            }else if(item.getApproveStatus()<ArmingTaskEnum.WAIT_SPY_TYPE.ordinal()){
                                operation.set("通过市局警种审核");
                                List<LfZdryEntity> zdrys = zdryList.get(item.getSpId());
                                if(!zdrys.isEmpty()){
                                    if(zdrys.get(0).getRylbx().contains("涉恐"))
                                        item.setApproveStatus(ArmingTaskEnum.FINISH_TYPE.ordinal());
                                    else
                                        item.setApproveStatus(item.getApproveStatus()+1);
                                }else
                                    item.setApproveStatus(item.getApproveStatus()+1);
                            } else{
                                operation.set("通过情报中心审核");
                                item.setApproveStatus(ArmingTaskEnum.FINISH_TYPE.ordinal());
                            }
                        }
                        //保存log
                        LfZdryArmingTaskOperateLog log = new LfZdryArmingTaskOperateLog();
                        log.setId(String.valueOf(KeyWorker.nextId()));
                        log.setDescription(description);
                        log.setOperateDateTime(LocalDateTime.now());
                        log.setTaskId(item.getAtId());
                        log.setRid(item.getId());
                        log.setSpId(item.getSpId());
                        if(accountBo!=null){
                            log.setOperator(accountBo.getPersonBo().getName());
                            log.setOperatorDept(accountBo.getOrganizationBo().getName());
                        }
                        log.setOperation(operation.get());
                        logs.add(log);
                    }).collect(Collectors.toList());
            if(!passEntities.isEmpty())
                this.updateBatchById(passEntities);
        }else if(Integer.valueOf(2).equals(status)){//退回
            List<ArmingTaskRelationEntity> passEntities = relationEntities.stream()
                    .filter(item->item.getApproveStatus()<ArmingTaskEnum.RECALL_TYPE.ordinal())
                    .peek(item->{
                        item.setDescription(description);
                        if(item.getApproveStatus()<ArmingTaskEnum.WAIT_POLICE_TYPE.ordinal()){
                            operation.set("区县警种退回");
                        }else if(item.getApproveStatus()<ArmingTaskEnum.WAIT_SPY_TYPE.ordinal()){
                            operation.set("市局警种退回");
                        }else{
                            operation.set("情报中心退回");
                        }
                        item.setApproveStatus(ArmingTaskEnum.RECALL_TYPE.ordinal());
                        //保存log
                        LfZdryArmingTaskOperateLog log = new LfZdryArmingTaskOperateLog();
                        log.setId(String.valueOf(KeyWorker.nextId()));
                        log.setDescription(description);
                        log.setOperateDateTime(LocalDateTime.now());
                        log.setTaskId(item.getAtId());
                        log.setRid(item.getId());
                        log.setSpId(item.getSpId());
                        if(accountBo!=null){
                            log.setOperator(accountBo.getPersonBo().getName());
                            log.setOperatorDept(accountBo.getOrganizationBo().getName());
                        }
                        log.setOperation(operation.get());
                        logs.add(log);
                    }).collect(Collectors.toList());
            if(!passEntities.isEmpty())
                this.updateBatchById(passEntities);
        }else if(Integer.valueOf(3).equals(status)){//撤销通过
            List<ArmingTaskRelationEntity> passEntities = relationEntities.stream()
                    .filter(item->item.getApproveStatus()>=ArmingTaskEnum.REQUEST_REBACK.ordinal() && item.getApproveStatus()<ArmingTaskEnum.REBACK_FINISH_TYPE.ordinal())
                    .peek(item->{
                        item.setDescription(description);
                        if(item.getApproveStatus().equals(ArmingTaskEnum.REBACK_RECALL_TYPE.ordinal())) {
                            item.setApproveStatus(ArmingTaskEnum.WAIT_POLICE_TYPE_REBACK.ordinal());
                        } else{
                            if(item.getApproveStatus()<ArmingTaskEnum.WAIT_POLICE_TYPE_REBACK.ordinal()){
                                operation.set("通过区县警种撤销审核");
                                item.setApproveStatus(item.getApproveStatus()+1);
                            }else{
                                operation.set("通过市局警种撤销审核");
                                item.setApproveStatus(ArmingTaskEnum.REBACK_FINISH_TYPE.ordinal());
                            }
//                            else if(item.getApproveStatus()<ArmingTaskEnum.WAIT_SPY_TYPE_REBACK.ordinal()){
//                                operation.set("通过市局警种撤销审核");
//                                List<LfZdryEntity> zdrys = zdryList.get(item.getSpId());
//                                if(!zdrys.isEmpty()){
//                                    if(zdrys.get(0).getRylbx().contains("涉恐"))
//                                        item.setApproveStatus(ArmingTaskEnum.REBACK_FINISH_TYPE.ordinal());
//                                    else
//                                        item.setApproveStatus(item.getApproveStatus()+1);
//                                }else
//                                    item.setApproveStatus(item.getApproveStatus()+1);
//                            }
//                            else{
//                                operation.set("通过市局警种撤销审核");
//                                item.setApproveStatus(ArmingTaskEnum.REBACK_FINISH_TYPE.ordinal());
//                            }
                        }
                        //保存log
                        LfZdryArmingTaskOperateLog log = new LfZdryArmingTaskOperateLog();
                        log.setId(String.valueOf(KeyWorker.nextId()));
                        log.setDescription(description);
                        log.setOperateDateTime(LocalDateTime.now());
                        log.setTaskId(item.getAtId());
                        log.setRid(item.getId());
                        log.setSpId(item.getSpId());
                        if(accountBo!=null){
                            log.setOperator(accountBo.getPersonBo().getName());
                            log.setOperatorDept(accountBo.getOrganizationBo().getName());
                        }
                        log.setOperation(operation.get());
                        logs.add(log);
                    }).collect(Collectors.toList());
            if(!passEntities.isEmpty())
                this.updateBatchById(passEntities);
        }else{//撤销退回
            List<ArmingTaskRelationEntity> passEntities = relationEntities.stream()
                    .filter(item->item.getApproveStatus()>ArmingTaskEnum.REQUEST_REBACK.ordinal() && item.getApproveStatus()<ArmingTaskEnum.REBACK_FINISH_TYPE.ordinal())
                    .peek(item->{
                        item.setDescription(description);
                        if(item.getApproveStatus()<ArmingTaskEnum.WAIT_POLICE_TYPE_REBACK.ordinal()){
                            operation.set("区县警种退回撤销请求");
                        }
//                        else if(item.getApproveStatus()<ArmingTaskEnum.WAIT_POLICE_TYPE_REBACK.ordinal()){
//                            operation.set("市局警种退回撤销请求");
//                        }
                        else{
                            operation.set("市局警种退回撤销请求");
                        }
                        item.setApproveStatus(ArmingTaskEnum.FINISH_TYPE.ordinal());
                        //保存log
                        LfZdryArmingTaskOperateLog log = new LfZdryArmingTaskOperateLog();
                        log.setId(String.valueOf(KeyWorker.nextId()));
                        log.setDescription(description);
                        log.setOperateDateTime(LocalDateTime.now());
                        log.setTaskId(item.getAtId());
                        log.setRid(item.getId());
                        log.setSpId(item.getSpId());
                        if(accountBo!=null){
                            log.setOperator(accountBo.getPersonBo().getName());
                            log.setOperatorDept(accountBo.getOrganizationBo().getName());
                        }
                        log.setOperation(operation.get());
                        logs.add(log);
                    }).collect(Collectors.toList());
            if(!passEntities.isEmpty())
                this.updateBatchById(passEntities);
        }
        if(!logs.isEmpty())
            logService.saveBatch(logs);
    }

    @Override
    public List<LfZdryArmingTaskOperateLog> getLogs(String rid) {
        return logService.list(new QueryWrapper<LfZdryArmingTaskOperateLog>().lambda().eq(LfZdryArmingTaskOperateLog::getRid,rid).orderByDesc(LfZdryArmingTaskOperateLog::getOperateDateTime));
    }

    @Override
    public List<Map<String,Object>> getReportedOrg(String taskId) {
        return this.getBaseMapper().getReportedOrg(taskId);
    }
}
